<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="用户名" prop="username">
        <el-input
            v-model="queryParams.username"
            placeholder="请输入用户名"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="角色" prop="remark">
        <el-select
            v-model="queryParams.remark"
            placeholder="请选择角色"
            clearable
            style="width: 120px"
        >
          <el-option label="学校管理员" value="学校管理员"/>
          <el-option label="教师" value="教师"/>
          <el-option label="学生" value="学生"/>
        </el-select>
      </el-form-item>
      <el-form-item label="姓名" prop="fullName">
        <el-input
            v-model="queryParams.fullName"
            placeholder="请输入姓名"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input
          v-model="queryParams.email"
          placeholder="请输入邮箱"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="电话" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入电话"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="最后登录时间" prop="lastLogin">
        <el-date-picker clearable
          v-model="queryParams.lastLogin"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择最后登录时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['schoolmanage:users:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['schoolmanage:users:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['schoolmanage:users:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['schoolmanage:users:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="usersList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="学校用户ID" align="center" prop="schoolUserId" />
      <el-table-column label="所属学校ID" align="center" prop="schoolId" />
      <!-- 新增学校名称列 -->
      <el-table-column label="所属学校名称" align="center" prop="schoolName" />
      <el-table-column label="用户名" align="center" prop="username" />
      <!-- 移除密码哈希列（或隐藏） -->
      <el-table-column label="角色" align="center" prop="remark" />
      <el-table-column label="姓名" align="center" prop="fullName" />
      <el-table-column label="邮箱" align="center" prop="email" />
      <el-table-column label="电话" align="center" prop="phone" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <el-tag :type="scope.row.status === '0' ? 'success' : 'danger'">
            {{ scope.row.status === '0' ? '可用' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="最后登录时间" align="center" prop="lastLogin" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.lastLogin, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['schoolmanage:users:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['schoolmanage:users:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改学校端用户对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="usersRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="所属学校ID" prop="schoolId">
          <el-input v-model="form.schoolId" placeholder="请输入所属学校ID" disabled />
        </el-form-item>
        <el-form-item label="邮箱" prop="email" required>
          <el-input v-model="form.email" placeholder="请输入邮箱" @blur="generateUsername" />
        </el-form-item>
        <el-form-item label="角色" prop="remark" required>
          <el-select v-model="form.remark" placeholder="请选择角色">
            <el-option label="学校管理员" value="学校管理员"/>
            <el-option label="教师" value="教师"/>
            <el-option label="学生" value="学生"/>
          </el-select>
        </el-form-item>
        <el-form-item label="姓名" prop="fullName" required>
          <el-input v-model="form.fullName" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="电话" prop="phone" required>
          <el-input v-model="form.phone" placeholder="请输入电话" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="0">可用</el-radio>
            <el-radio label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="最后登录时间" prop="lastLogin" v-if="form.schoolUserId">
          <el-date-picker clearable
                          v-model="form.lastLogin"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择最后登录时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Users">
import { listUsers, getUsers, delUsers, addUsers, updateUsers} from "@/api/schoolmanage/users"
import { ref, reactive, toRefs } from 'vue';
const { proxy } = getCurrentInstance()
import {parseTime} from "../../../utils/ruoyi.js";

const usersList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {
    schoolUserId: null,
    schoolId: null,
    username: null, // 自动生成，不显示在表单中
    passwordHash: null,
    remark: null, // 新增角色字段
    fullName: null,
    email: null,
    phone: null,
    createTime: null,
    lastLogin: null,
    status: '0'
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    schoolId: null,
    username: null,
    remark: null, // 新增角色查询条件
    fullName: null,
    email: null,
    phone: null,
    lastLogin: null,
    status: null
  },
  rules: {
    schoolId: [
      { required: true, message: "所属学校ID不能为空", trigger: "blur" }
    ],
    remark: [
      { required: true, message: '请选择角色', trigger: 'change' }
    ],
    email: [
      { required: true, message: '请输入邮箱', trigger: 'blur' },
      { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
    ],
    fullName: [
      { required: true, message: "姓名不能为空", trigger: "blur" }
    ],
    phone: [
      { required: true, message: "电话不能为空", trigger: "blur" },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ],
    status: [
      { required: true, message: "请选择状态", trigger: "change" }
    ]
  }
})
/** 根据邮箱自动生成用户名 */
function generateUsername() {
  if (form.value.email && !form.value.schoolUserId) {
    const emailParts = form.value.email.split('@');
    if (emailParts.length === 2) {
      const prefix = emailParts[0];
      const domain = emailParts[1].split('.')[0];
      form.value.username = `${domain}_${prefix}`.toLowerCase();
    }
  }
}
const { queryParams, form, rules } = toRefs(data)

/** 查询学校端用户列表 */
function getList() {
  loading.value = true
  const schoolId = useExampleStore().school;
  console.log('当前 schoolId..........:',schoolId);
  queryParams.value.schoolId = useExampleStore().school
  listUsers(queryParams.value).then(response => {
    usersList.value = response.rows
    total.value = response.total
    loading.value = false
  }).catch(error=>{
    console.error("获取列表失败：",error);
    loading.value = false;
  })
}
// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    schoolUserId: null,
    schoolId: null,
    username: null,
    passwordHash: null,
    remark: null,
    fullName: null,
    email: null,
    phone: null,
    createTime: null,
    lastLogin: null
  }
  proxy.resetForm("usersRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.schoolUserId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  form.value.schoolId = useExampleStore().school // 设置当前学校ID
  open.value = true
  title.value = "添加学校端用户"
  // 添加时清空最后登录时间
  form.value.lastLogin = null
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _schoolUserId = row.schoolUserId || ids.value
  getUsers(_schoolUserId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改学校端用户"
    // 修改时保留原有最后登录时间
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["usersRef"].validate(valid => {
    if (valid) {
      if (form.value.schoolUserId != null) {
        updateUsers(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addUsers(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _schoolUserIds = row.schoolUserId || ids.value
  proxy.$modal.confirm('是否确认删除学校端用户编号为"' + _schoolUserIds + '"的数据项？').then(function() {
    return delUsers(_schoolUserIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('schoolmanage/users/export', {
    ...queryParams.value
  }, `users_${new Date().getTime()}.xlsx`)
}

import { onMounted } from 'vue';
import {useExampleStore} from "@/stores/exampleStore.js";
onMounted(() => {
  getList()
});
</script>
